package com.xiaolong.websocket.core;

import com.xiaolong.websocket.context.MessageHandle;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class WebsocketMessageHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private MessageHandle messageHandle;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    Map<Long, Channel> map = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext context, TextWebSocketFrame text) throws Exception {
        Object handle = messageHandle.handle(text.text());
        context.writeAndFlush(handle);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                ctx.channel().close();
            }
        }

    }

}
